package leetcode

import "fmt"

// ListNode link list node
type ListNode struct {
	Val  int
	Next *ListNode
}

// Print print the list node value
func (l *ListNode) Print() {
	var n = l
	for true {
		if n != nil {
			fmt.Printf("%v->", n.Val)
			n = n.Next
		} else {
			fmt.Print("NULL")
			break
		}
	}
}

// Count get list Count
func (l *ListNode) Count() int {
	count := 0
	var n = l
	for true {
		if n != nil {
			count++
			n = n.Next
		} else {
			break
		}
	}
	return count
}

// RotateRight Rotate link node to Right
func RotateRight(head *ListNode, k int) *ListNode {
	l := head.Count()
	if l == 0 {
		return head
	}
	root := &ListNode{
		Val:  -1,
		Next: head,
	}
	for i := 0; i < k%l; i++ {
		curNode := root.Next
		for true {
			if curNode == nil {
				break
			}
			nextNode := curNode.Next
			if nextNode == nil {
				break
			}
			if nextNode.Next == nil {
				nextNode.Next = root.Next
				root.Next = nextNode
				curNode.Next = nil
			}
			curNode = curNode.Next
		}
	}
	return root.Next
}
